/**
 * 作者: dailc
 * 时间: 2016-05-24
 * 描述: 首页 
 */
define(function(require, exports, module) {
	"use strict";
	//每一个页面都要引入的工具类
	var CommonTools = require('CommonTools_Core');
	//window操作
	var WindowTools = require('WindowTools_Core');
	var StorageTools = require('StorageTools_Core');
	//UI的初始化
	var UITools = require('UITools_Core');
	var GallerySliderTools = require('GallerySliderTools_Core');

	var baseService = require("Base_Service");
	var systemService = require("System_Service");
	var studyLogService = require("StudyLogs_Service");
	var examBookingService = require("ExamBooking_Service");
	//用户数据
	var userInfo;

	//每一个页面都要引入的工具类
	// initready 要在所有变量初始化做完毕后
	CommonTools.initReady(initData);
	/**
	 * @description 初始化数据,结合initReady使用
	 * plus情况为plusready
	 * 其它情况为直接初始化
	 */
	function initData(isPlus) {
		//plus下仅支持竖屏显示-设为竖屏,false为横屏
		CommonTools.lockOrientation(true);
		//引入必备文件,下拉刷新依赖于mui
		CommonTools.importFile([
			'js/libs/mui.min.js',
			'js/libs/mui.picker.min.js'
		], function() {
			userInfo = baseService.getUser();
			window.addEventListener("mainrefresh", function(e) {
				console.log('refresh');
				location.reload();
			});
			initHomePage(); //初始化页面
			initListeners(); //监听事件
			//plus下双击返回退出-需要Mui
			WindowTools.dbClickExit();
			console.log(JSON.stringify(mui.os));
			if(isPlus) {
				WindowTools.preloadTemplate();
				//关闭splash
				plus.navigator.closeSplashscreen();
			}
		});
	}

	/*
	 * @description 首页初始化
	 * */
	function initHomePage() {
		mui('.mui-scroll-wrapper').scroll({
			deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
		});
		openLogin();
		openUsedcar();
		openDrivingSchool();
		openFindCoach(); //找教练
		openMoni(); //打开模拟考试
		openZiZhuApply(); //自主报名
		openTuanGouApply(); //团购报名
		openChuanTongApply(); //传统报名
		openGongXiangTrain(); //购买学时
		openApplyNote(); //购买学时
		openOrderStudy(); //预约学车
		openLearnPort(); //学习档案
		openExamBooking(); //考试预约记录
		openAbout() //关于
		me();
		initGallerySlider(); //首页轮播图
		initExamBooking(); //初始化预约考试表单

		initLastPageClick();
		mui(".mui-bar-tab").on('tap', '.mui-tab-item', function() {
			console.log(this.getAttribute('data'));
			if(this.getAttribute('data') == 'home' || this.getAttribute('data') == 'phone') {
				console.log('aaaa');
			}else{
				if(userInfo == null) {
					closeAllPage('./account/login.html');
				}
			}

		});
	}

	function initLastPageClick() {
		mui(".change").on('tap', '#change', function() {
			WindowTools.createWin(null, './account/change_password.html', null, {});
		});
		mui(".change").on('tap', '#exit', function() {
			baseService.clear();
			//			if(plus) {
			//				plus.currentWebview().reload();
			closeAllPage('./account/login.html');
			//			}
		});
	}

	/**
	 * @description 监听
	 */
	function initListeners() {
		mui("#exam_ddlPlace")[0].addEventListener("change", function() {
			console.log('aaasaa');
			initCoach();
		});
		mui("#exam_ddlCourse")[0].addEventListener("change", function() {
			initCoach();
		});
		mui("#exam_btnSubmit")[0].addEventListener("tap", function() {
			if(mui("#exam_ddlPlace")[0].value == '') {
				mui.toast('场地不能为空');
				return;
			}
			if(mui("#exam_ddlCoach")[0].value == '') {
				mui.toast('教练不能为空');
				return;
			}
			if(mui("#exam_ddlCourse")[0].value == '') {
				mui.toast('科目不能为空');
				return;
			}
			var data = {
				PlaceID: mui("#exam_ddlPlace")[0].value,
				CoachID: mui("#exam_ddlCoach")[0].value,
				CourseType: mui("#exam_ddlCourse")[0].value
			};
			examBookingService.add(data, function(retval) {
				debugger;
				WindowTools.createWin(null, "exam/exambooking_detail.html", {
					'mid': retval.ExamBookingID
				}, {});
			});
		});
	}

	/**
	 * @description 初始化预约考试表单
	 * */
	function initExamBooking() {
		mui('.exam-div').on('tap', '#place_reload', function() {
			document.getElementById('place_reload').style.display = 'none';
			initPlace();
		});
		initPlace(); //初始化场地
	}

	/**
	 *@description 日期选择 
	 */
	function showDataPicker() {
		mui('.mui-content').on('tap', '#exam_dateExam', function() {
			var dtPicker = new mui.DtPicker({
				type: "date",
				beginDate: new Date()
			});
			dtPicker.show(function(selectItems) {
				mui("#exam_dateExam")[0].setAttribute("data-exam-time", selectItems.text);
				mui("#exam_dateExam")[0].innerHTML = selectItems.text;
			})
		});
	}
	/**
	 *@description 初始化场地 
	 */
	function initPlace() {
		mui("#exam_ddlPlace")[0].innerHTML = "";
		userInfo = baseService.getUser();
		if(userInfo == null) {
			return;
		}
		systemService.getPlaces(userInfo.DrivingID, function(retval) {
			//			console.log(retval);
			var optionStr = "";
			if(retval) {
				if(retval.length == 0) {
					document.getElementById('place_reload').style.display = '';
				}
				for(var index in retval) {
					var item = retval[index];
					optionStr += "<option value='" + item.id + "'>" + item.name + "</option>";
				}
				mui("#exam_ddlPlace")[0].innerHTML = optionStr;
				initCoach();
			}
		}, function() {
			document.getElementById('place_reload').style.display = '';
		});
	}

	/**
	 *@description 初始化教练 
	 */
	function initCoach() {
		mui("#exam_ddlCoach")[0].innerHTML = "";
		studyLogService.getCoachs(0, mui("#exam_ddlPlace")[0].value, mui("#exam_ddlCourse")[0].value, true, function(retval) {
			var optionStr = "";
			if(retval) {
				for(var index in retval) {
					var item = retval[index];
					optionStr += "<option value='" + item.CoachID + "'>" + item.Name + "</option>";
				}
				mui("#exam_ddlCoach")[0].innerHTML = optionStr;
			}
		});
	}

	function openLogin() {
		mui('.mui-bar-nav').on('tap', '#home_login', function() {
			if(userInfo == null) {
				closeAllPage('./account/login.html');
			}
		});
		if(userInfo == null) {
			document.getElementById('home_login').style.display = 'block';
		} else {
			console.log('a');
			document.getElementById('home_login').style.display = 'none';
			console.log('b');
		}
	}

	function openAbout() {
		mui('.mui-content').on('tap', '#home_about', function() {
			var style = {};
			WindowTools.createWin(null, "./about/demo_about.html", null, style);
		});
	}

	function openUsedcar() {
		mui('.mui-content').on('tap', '#home_usedcar', function() {
			var style = {};
			WindowTools.createWin(null, "./usedcar/car_brand.html", null, style);
		});
	}

	function openOrderStudy() {
		mui('.mui-content').on('tap', '#home_order_study', function() {
			if(userInfo == null) {
				closeAllPage('./account/login.html');
				return;
			}
			var style = {};
			WindowTools.createWin(null, "./school/orderstudy.html", null, style);
		});
	}

	function openDrivingSchool() {
		mui('.mui-content').on('tap', '#home_find_place', function() {
			var style = {};
			WindowTools.createWin(null, "./map/demo_map_baidumapH5.html", null, style);
		});
	}

	function openFindCoach() {
		mui('.mui-content').on('tap', '#home_find_coach', function() {
			if(userInfo == null) {
				closeAllPage('./account/login.html');
				return;
			}
			var style = {};
			WindowTools.createWin(null, "./exam/find_coach.html", null, style);
		});
	}

	function openMoni() {
		mui('.mui-content').on('tap', '#home_moni', function() {
			var style = {};
			WindowTools.createWin(null, "./moni/moni.html", null, style);
		});
	}

	function openZiZhuApply() {
		mui('.mui-content').on('tap', '#home_zizhu_apply', function() {
			var style = {};
			WindowTools.createWin(null, "./apply/zizhu_apply_select.html", null, style);
		});
	}

	function openTuanGouApply() {
		mui('.mui-content').on('tap', '#home_tuangou_apply', function() {
			var style = {};
			WindowTools.createWin(null, "./apply/tuangou_apply_select.html", null, style);
		});
	}

	function openChuanTongApply() {
		mui('.mui-content').on('tap', '#home_chuantong_apply', function() {
			var style = {};
			WindowTools.createWin(null, "./apply/chuantong_apply_select.html", null, style);
		});
	}

	function openApplyNote() {
		mui('.mui-content').on('tap', '#home_apply_note', function() {
			var style = {};
			WindowTools.createWin(null, "./apply/apply_note.html", null, style);
		});
	}

	function openGongXiangTrain() {
		mui('.mui-content').on('tap', '#home_train', function() {
			var style = {};
			WindowTools.createWin(null, "./apply/zizhu_apply_select.html", null, style);
		});
	}

	function openLearnPort() {
		mui('.mui-content').on('tap', '#me_learn_port', function() {
			var style = {};
			WindowTools.createWin(null, "./learnPort/learn_port_current.html", null, style);
		});
	}

	function openExamBooking() {
		mui('.mui-content').on('tap', '#me_exam_booking', function() {
			var style = {};
			WindowTools.createWin(null, "./exam/exambooking_history.html", null, style);
		});
	}

	function me() {
		if(userInfo != null) {
			document.getElementById('username').innerHTML = '用户名:' + userInfo.UserName;
			document.getElementById('city').innerHTML = '城市:' + userInfo.CityName;
		}
		mui('#city')[0].onclick = function() {
			console.log('hhhh');
			WindowTools.createWin(null, "./account/city_select.html", null, {});
		}
		mui(".me-link-to").on('tap', '.mui-table-view-cell', function() {
			var linkUrl = this.getAttribute('link-url');
			var style = {};
			WindowTools.createWin(null, linkUrl, null, style);
		});
	}

	/**
	 * @description 初始化图片轮播
	 */
	function initGallerySlider() {
		createGallerySliderDefault();
	}

	/**
	 * @description 创建默认图片轮播
	 */
	function createGallerySliderDefault() {
		//默认轮播数据
		var GalleryData = [{
			id: "testgallery1",
			title: "", //为空
			url: "../img/banner/1.jpeg"
		}, {
			id: "testgallery2",
			title: "", //为空
			url: "../img/banner/2.jpeg"
		}, {
			id: "testgallery3",
			title: "", //为空
			url: "../img/banner/3.jpeg"
		}, {
			id: "testgallery4",
			title: "", //为空
			url: "../img/banner/4.jpeg"
		}];
		var options = {
			isLoop: true,
			isAuto: true,
			autoTime: 3000,
			//图片的最大高度,可以不传
			maxImgHeight: '100%',
			//如果是每一个item有多张图,那么决定每一行显示几张图
			perLineItem: 2,
			//是否显示下面的Indicator
			isShowIndicator: true,
			//是否显示下面的翻页Indicator
			isShowPageIndicator: false
		};
		addGallery(GalleryData, options);
	}

	/**
	 * @description 添加轮播图片工具方法
	 * @param {JSON} GalleryData
	 * @param {JSON} options 对应参数
	 */
	function addGallery(GalleryData, options) {
		var myGallery = GallerySliderTools.addGalleryLandscape('#gallerySlider', GalleryData, function(e, id) {
			console.log("点击:" + id);
		}, options);
	}

	function closeAllPage(url) {
		if(mui.os.ios) {
			var curr = plus.webview.currentWebview();
			var wvs = plus.webview.all();
			for(var i = 0, len = wvs.length; i < len; i++) {
				//关闭除setting页面外的其他页面
				if(wvs[i].getURL() == curr.getURL())
					continue;
				plus.webview.close(wvs[i]);
			}
			plus.webview.open(url);
			//curr.reload();
			//curr.close();
		} else {
			var style = {};
			WindowTools.createWin(null, url, null, style);
			curr.reload();
		}

	}

});